package com.atguigu.gmall.pms.service.impl;

import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.pms.feign.GmallSmsClient;
import com.atguigu.gmall.pms.mapper.SkuMapper;
import com.atguigu.gmall.pms.mapper.SpuDescMapper;
import com.atguigu.gmall.pms.service.*;
import com.atguigu.gmall.pms.vo.SkuVo;
import com.atguigu.gmall.pms.vo.SpuAttrValueVo;
import com.atguigu.gmall.pms.vo.SpuVo;
import com.atguigu.gmall.sms.vo.SkuSalesVo;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gmall.common.bean.PageResultVo;
import com.atguigu.gmall.common.bean.PageParamVo;

import com.atguigu.gmall.pms.mapper.SpuMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuService")
@Slf4j
public class SpuServiceImpl extends ServiceImpl<SpuMapper, SpuEntity> implements SpuService {

    @Autowired
    private SpuDescService spuDescService;
    @Autowired
    private SpuAttrValueService spuAttrValueService;
    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuAttrValueService skuAttrValueService;
    @Autowired
    private GmallSmsClient gmallSmsClient;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageResultVo queryPage(PageParamVo paramVo) {
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                new QueryWrapper<SpuEntity>()
        );

        return new PageResultVo(page);
    }

    @Override
    public PageResultVo querySpuByCidAndPage(PageParamVo paramVo, Long categoryId) {
        QueryWrapper<SpuEntity> wrapper = new QueryWrapper<>();
        // 如果category不为0，需要查本类
        if (categoryId != 0) {
            wrapper.eq("category_id", categoryId);
        }
        // 关键字
        String key = paramVo.getKey();
        if (StringUtils.isNotBlank(key)) {
            // wrapper后面直接写条件，条件之间默认是and关系，并且都没有括号
            wrapper.and(t -> t.eq("id", key).or().like("name", key));
        }
        IPage<SpuEntity> page = this.page(
                paramVo.getPage(),
                wrapper
        );
        return new PageResultVo(page);
    }

    /**@Transactional(noRollbackFor = Exception.class)所有的异常都不 会回滚
     * @Transactional(timeout = 3) 以秒为单位 超时事务
     *  @Transactional(readOnly = true) 只读事务
     */
    @GlobalTransactional
    @Override
    public void bigSave(SpuVo spu) {

        // 1.保存spu相关的三张表
        // 1.1 保存pms_spu
        Long spuId = saveSpuInfo(spu);

        // 1.2 保存pms_spu_desc
        this.spuDescService.saveSpuDesc(spu, spuId);

//        int i=1/0;

        // 1.3 保存pms_spu_attr_value
        saveBaseAttrs(spu);

        // 2.保存sku相关的三张表
        // 3.保存营销信息相关的三张表
        saveSkuINfo(spu, spuId);

        this.sendMessage(spuId,"insert");
    }

    private void sendMessage(Long id, String type){
        // 发送消息
        try {
            this.rabbitTemplate.convertAndSend("PMS_ITEM_EXCHANGE", "item." + type, id);
        } catch (Exception e) {
            log.error("{}商品消息发送异常，商品id：{}", type, id, e);
        }
    }
    private void saveSkuINfo(SpuVo spu, Long spuId) {
        List<SkuVo> skus = spu.getSkus();
        if (CollectionUtils.isEmpty(skus)){
            return;
        }
        // 遍历sku,保存到pms_sku
        skus.forEach(skuVo -> {
            // 2.1 保存pms_sku
            skuVo.setSpuId(spuId);
            skuVo.setCategoryId(spu.getCategoryId());
            skuVo.setBrandId(spu.getBrandId());
            List<String> images = skuVo.getImages();
            if (!CollectionUtils.isEmpty(images)){
                skuVo.setDefaultImage(StringUtils.isBlank(skuVo.getDefaultImage()) ? images.get(0) : skuVo.getDefaultImage());
            }
            this.skuMapper.insert(skuVo);
            Long skuId = skuVo.getId();
            // 2.2 保存pms_sku_images
            if (!CollectionUtils.isEmpty(images)){
                this.skuImagesService.saveBatch(images.stream().map(image ->{
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setSort(0);
                    skuImagesEntity.setUrl(image);
                    // 判断是否是默认图片 图片地址是否相同
                    skuImagesEntity.setDefaultStatus(StringUtils.equals(skuVo.getDefaultImage(),image) ? 1 : 0);
                    return skuImagesEntity;
                }).collect(Collectors.toList()));
            }
            // 2.3 保存pms_sku_attr_value
            List<SkuAttrValueEntity> saleAttrs = skuVo.getSaleAttrs();
            if (!CollectionUtils.isEmpty(saleAttrs)) {
                saleAttrs.forEach(skuAttrValueEntity -> {
                    skuAttrValueEntity.setSkuId(skuId);
                });
            }
            this.skuAttrValueService.saveBatch(saleAttrs);
            // 3.保存营销信息相关的三张表
            SkuSalesVo skuSalesVo = new SkuSalesVo();
            BeanUtils.copyProperties(skuVo,skuSalesVo);
            skuSalesVo.setSkuId(skuId);
            this.gmallSmsClient.saveSales(skuSalesVo);
        });
    }

    private void saveBaseAttrs(SpuVo spu) {
        List<SpuAttrValueVo> baseAttrs = spu.getBaseAttrs();
        if (!CollectionUtils.isEmpty(baseAttrs)) {
            // 把SpuAttrValueVo集合转化为SpuAttrValueEntity集合
            List<SpuAttrValueEntity> spuAttrValueEntities = baseAttrs.stream()
                    .filter(spuAttrValueVo -> spuAttrValueVo.getAttrValue() != null)
                    .map(SpuAttrValueVo -> {
                        SpuAttrValueEntity spuAttrValueEntity = new SpuAttrValueEntity();
                        BeanUtils.copyProperties(SpuAttrValueVo, spuAttrValueEntity);
                        spuAttrValueEntity.setSpuId(spu.getId());
                        spuAttrValueEntity.setSort(0);
                        return spuAttrValueEntity;
                    }).collect(Collectors.toList());
            this.spuAttrValueService.saveBatch(spuAttrValueEntities);
        }
    }

    private Long saveSpuInfo(SpuVo spu) {
        spu.setCreateTime(new Date());
        spu.setUpdateTime(spu.getCreateTime());
        this.save(spu);
        return spu.getId();
    }

}